//
//  YSShareVew.m
//  newYueLvHui
//
//  Created by Apple on 2020/9/12.
//  Copyright © 2020 Facebook. All rights reserved.
//

#import "YSShareVew.h"
#import "YSShareItemButtom.h"

@interface YSShareVew ()<UIGestureRecognizerDelegate>
/// 底部背景
@property (nonatomic,strong) UIView *contrainView;
/// 平台背景
@property (nonatomic,strong) UIScrollView *scrollView;
/// 取消
@property (nonatomic,strong) UIButton *cancelBtn;
/// 标题
@property (nonatomic,strong) UILabel *titleLab;
/// 列数
@property (nonatomic,assign) NSInteger column;
/// 行数
@property (nonatomic,assign) NSInteger row;
/// 分享平台
@property (nonatomic,strong) NSArray *platforms;
/// 海报
@property (nonatomic,strong) UIImageView *placardView;
/// 是否显示海报
@property (nonatomic,assign) BOOL isShowPlacard;

@property (nonatomic, strong) NSArray <YSShareModel *> *customConfig;

@end

#define TitleH  50
#define CanceH  44
#define ItemW   75
#define ItemH   65
#define RowSpacing 25

@implementation YSShareVew

- (instancetype)initWithColumn:(NSInteger)column row:(NSInteger)row platforms:(NSArray *)platforms customConfig:(NSArray <YSShareModel *> *)customConfig {
    
    if (self = [super init]) {
        self.frame = UIScreen.mainScreen.bounds;
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        self.alpha = 0;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancelAction)];
        tap.delegate = self;
        [self addGestureRecognizer:tap];
        
        self.column = column ? column : 3;
        if (_column > 4) {
            _column = 4;
        }
        self.row  = row ? row : 1;
        if (_row > 2) {
            _row = 2;
        }
        self.customConfig = customConfig;
        self.platforms = platforms;
        [self makeUI];
        [self makeLayout];
        [self createItemViews];
    }
    return self;
}

- (instancetype)initWithColumn:(NSInteger)column row:(NSInteger)row platforms:(NSArray *)platforms
{
    if (self = [super init]) {
        self.frame = UIScreen.mainScreen.bounds;
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        self.alpha = 0;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancelAction)];
        tap.delegate = self;
        [self addGestureRecognizer:tap];
        
        self.column = column ? column : 3;
        if (_column > 4) {
            _column = 4;
        }
        self.row  = row ? row : 1;
        if (_row > 2) {
            _row = 2;
        }
        self.platforms = platforms;
        [self makeUI];
        [self makeLayout];
        [self createItemViews];
    }
    return self;
}


- (void)makeUI
{
    [self addSubview:self.contrainView];
    [self.contrainView addSubview:self.titleLab];
    [self.contrainView addSubview:self.scrollView];
    [self.contrainView addSubview:self.cancelBtn];
}

- (void)makeLayout
{
    self.contrainView.frame = CGRectMake(0, [YSFrameAdapter kWindowHeight], [YSFrameAdapter kWindowWidth], TitleH + CanceH + RowSpacing + (RowSpacing + ItemH) * _row + [YSFrameAdapter kIPhoneXBottomSafeHeight]);
    self.titleLab.frame = CGRectMake(0, 0, [YSFrameAdapter kWindowWidth], TitleH);
    self.scrollView.frame = CGRectMake(0, TitleH , [YSFrameAdapter kWindowWidth], self.contrainView.ys_height - TitleH - CanceH);
    self.cancelBtn.frame = CGRectMake(0, self.contrainView.ys_height - CanceH - [YSFrameAdapter kIPhoneXBottomSafeHeight], [YSFrameAdapter kWindowWidth], CanceH);
}


- (void)createItemViews
{
    
    CGFloat w = [YSFrameAdapter kWindowWidth]/self.column;
    for (NSInteger i = 0; i < _platforms.count; i ++) {
        YSSharePlatformType platformType = (YSSharePlatformType)[_platforms[i] integerValue];
        YSShareItemButtom *btn = [self createButtonWithSharePlatformType:platformType];
        btn.frame = CGRectMake(i%_column * w + (w - ItemW)/2, RowSpacing + i/_column * (ItemH + RowSpacing), ItemW, ItemH);
        [self.scrollView addSubview:btn];
    }
}

- (YSShareItemButtom *)createButtonWithSharePlatformType:(YSSharePlatformType)platformType
{
    
    YSShareModel *tempModel = nil;
    for (int i = 0; i < [self.customConfig count]; i++) {
        YSShareModel * shareModel = [self.customConfig objectAtIndex:i];
        if (shareModel.platformType == platformType) {
            tempModel = shareModel;
            break;;
        }
    }

    YSShareModel *model = tempModel ?: [YSShareModel shareModelWithPlatformType:platformType];
    YSShareItemButtom *btn = [YSShareItemButtom buttonWithType:UIButtonTypeCustom];
    btn.model = model;
    [btn setTitleColor:[UIColor colorWithHexCode:@"#333333"] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont font_systemRegularFontWithNoScaleSize:12];
    [btn setImage:[UIImage ys_imageNamed:model.imgName bundle:@"YSShareModule" targetClass:[self class]] forState:UIControlStateNormal];
    [btn setTitle:model.title forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(buttonDidClickedAction:) forControlEvents:UIControlEventTouchUpInside];
    
    return btn;
}


#pragma mark---事件
- (void)buttonDidClickedAction:(YSShareItemButtom *)btn
{
    [self cancelAction];
    YSSharePlatformType type = btn.model.platformType;
    if (type == YS_SavePhoto) {
        if (self.savePhotoBlock && self.placardView.image) {
            self.savePhotoBlock(self.placardView.image);
        }
        return;
    }
    
    if (self.sharePlatformBlock) {
        self.sharePlatformBlock(type);
    }
    
    if (_isShowPlacard) {
        if (self.sharePlacardBlock) {
            self.sharePlacardBlock(type, self.placardView.image);
        }
    }
}

- (void)showSharePlatformView
{
    UIWindow *window = UIApplication.sharedApplication.delegate.window;
    if (self.superview) {
        return;
    }
    [window addSubview:self];
    self.alpha = 0;
    [UIView animateWithDuration:0.25 animations:^{
        self.alpha = 1;
        self.contrainView.ys_y = [YSFrameAdapter kWindowHeight] - self.contrainView.ys_height;
    }];
    
    _isShowPlacard = NO;
}

- (void)cancelAction
{
    [UIView animateWithDuration:0.25 animations:^{
        self.alpha = 0;
        self.contrainView.ys_y = [YSFrameAdapter kWindowHeight];
    } completion:^(BOOL finished) {
        [self.contrainView removeFromSuperview];
        [self removeFromSuperview];
    }];
}

- (void)showPlacardView
{
    [self showSharePlatformView];
    if (self.placardView.superview) {
        return;
    }
    [self addSubview:self.placardView];
    [self insertSubview:[self effectView] atIndex:0];
    self.placardView.frame = CGRectMake(50, [YSFrameAdapter kStatusBarHeight] + 25, [YSFrameAdapter kWindowWidth] - 100, [YSFrameAdapter kWindowHeight] - self.contrainView.ys_height - [YSFrameAdapter kStatusBarHeight] - 75);
    _isShowPlacard = YES;
}

- (void)setPlacardImage:(UIImage *)placardImage {
    
    self.placardView.image = placardImage;
}

- (void)setPlacard_url:(NSString *)placard_url
{
    [MBProgressHUD showHUDAddedTo:self.placardView animated:YES];
    [self.placardView sd_setImageWithURL:[NSURL URLWithString:placard_url] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.placardView animated:YES];
            self.placardView.image = image;
            self.placardView.transform = CGAffineTransformMakeScale(0.01, 0.01);
            [UIView animateWithDuration:0.25 animations:^{
                self.placardView.transform = CGAffineTransformMakeScale(1, 1);
            }];
        });
        
    }];
}

- (void)setAttrString:(NSAttributedString *)attrString
{
    if (attrString != nil) {
        self.titleLab.attributedText = attrString;
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([touch.view isDescendantOfView:self.contrainView] || [touch.view isDescendantOfView:self.placardView]) {
        return NO;
    }
    return YES;
}
#pragma mark---懒加载

- (UILabel *)titleLab
{
    if (!_titleLab) {
        _titleLab = [[UILabel alloc] init];
        _titleLab.text = @"分享";
        _titleLab.textAlignment = NSTextAlignmentCenter;
        _titleLab.font = [UIFont font_systemRegularFontWithNoScaleSize:15];
        _titleLab.textColor = [UIColor colorWithHexCode:@"#333333"];
        _titleLab.backgroundColor = [UIColor colorWithHexCode:@"#f8f8f8"];;
    }
    return _titleLab;
}

- (UIButton *)cancelBtn
{
    if (!_cancelBtn) {
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelBtn setTitleColor:[UIColor colorWithHexCode:@"#333333"] forState:UIControlStateNormal];
        _cancelBtn.backgroundColor = UIColor.whiteColor;
        _cancelBtn.titleLabel.font = [UIFont font_systemRegularFontWithNoScaleSize:15];
        [_cancelBtn addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];

    }
    return _cancelBtn;
}

- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.backgroundColor = [UIColor colorWithHexCode:@"#f8f8f8"];
        _scrollView.showsHorizontalScrollIndicator = NO;
    }
    return _scrollView;
}

- (UIView *)contrainView
{
    if (!_contrainView) {
        _contrainView = [UIView new];
        _contrainView.backgroundColor = UIColor.whiteColor;
        _contrainView.layer.masksToBounds = YES;
        _contrainView.layer.cornerRadius = 10;
    }
    return _contrainView;
}

- (UIImageView *)placardView
{
    if (!_placardView) {
        _placardView = [[UIImageView alloc] init];
//        _placardView.backgroundColor = UIColor.clearColor;
        _placardView.userInteractionEnabled = YES;
        _placardView.contentMode = UIViewContentModeScaleAspectFit;
    }
    return _placardView;
}

- (UIVisualEffectView *)effectView
{
    UIBlurEffect *blur = [UIBlurEffect effectWithStyle: UIBlurEffectStyleRegular];
    UIVisualEffectView *blurView = [[UIVisualEffectView alloc] initWithEffect: blur];
    blurView.frame = self.bounds;
    return blurView;
}

- (void)dealloc
{
    NSLog(@"%@已释放",NSStringFromClass(self.class));
}

@end
